package project1;


public abstract class IResponse extends Thread {
	
	protected byte[] data;
	protected ICommand comm;
	protected boolean dead;
	
	protected IResponse(byte[] data, ICommand command) {
		this.data = data;
		this.comm = command;
		this.dead = false;
	}
	
	public static IResponse createInstance(byte[] data, ICommand command) {
		int type = Util.readType(data);
		if (type == 0x02) {
			// Registered
			RegisteredResponse resp = new RegisteredResponse(data, command);
			RegisterCommand comm = (RegisterCommand) command;
			WaitResponseThread.rrtl.put(comm.getServiceName(), resp);
			return resp; 
		} else if (type == 0x04) {
			// FetchResponse
			return new FetchResponse(data, command);
		} else if (type == 0x07) {
			// ACK
			return new ACKResponse(data, command);
		} else {
			throw new IllegalArgumentException("Given type is not recognised as response type.");
		}
	}
	
	public abstract void run();
	
	public int getType() {
		return Util.readType(data);
	}
	
	public byte getSeqNum() {
		return Util.readSeqNumber(data);
	}
	
	public void close() {
		this.dead = true;
	}
	
	protected byte[] getResponse() {
		return data;
	}
}
